import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import NProgress from 'nprogress' // 引入进度条
import 'nprogress/nprogress.css' // 引入进度条样式

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home', // 默认显示首页的二级路由
    children: [
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        path: 'article-category',
        component: () => import('@/views/article/article-category.vue')
      },
      {
        path: 'article-list',
        component: () => import('@/views/article/article-list.vue')
      },
      {
        path: 'add-article',
        component: () => import('@/views/article/add-article.vue')
      },
      {
        path: 'base-info',
        component: () => import('@/views/user/base-info.vue')
      },
      {
        path: 'change-avatar',
        component: () => import('@/views/user/change-avatar.vue')
      },
      {
        path: 'reset-pass',
        component: () => import('@/views/user/reset-pass.vue')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/register',
    component: () => import('@/views/register')
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  }
]

const router = new VueRouter({
  routes
})

const whileList = ['/login', '/register', '/404']
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (store.state.user.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whileList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

export default router
